package com.darryring.fast.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.darryring.fast.R;
import com.darryring.fast.activitys.HomeActivity;
import com.darryring.fast.adapter.ContactAdapter;
import com.darryring.fast.util.DrawableUtil;
import com.darryring.libchat.ContactManager;
import com.darryring.libchat.LibChat;
import com.darryring.libmodel.entity.FContact;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hljdrl on 16/3/2.
 */
public class ContactFragment extends BaseFragment implements AdapterView.OnItemClickListener{


    ListView mListview;
    ContactManager<FContact> contactManager;
    private List<FContact> mContacts = new ArrayList<FContact>();
    ContactAdapter mContactAdapter;
    public ContactFragment(){
    }
    @SuppressLint("ValidFragment")
    public ContactFragment(String _title){
        setTitle(_title);
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(LibChat.chatClient!=null){
            contactManager = LibChat.chatClient.contactManager();
        }
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View _view = inflater.inflate(R.layout.fragment_contact,container,false);
        return _view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        View _view = getView();
        mListview = (ListView) _view.findViewById(R.id.listview_contact);
        //=====================================================================
        TypedArray ta = getActivity().getTheme().obtainStyledAttributes(R.styleable.FastColorTheme);
        int _defaultColor = Color.TRANSPARENT;
        int _selectColor = ta.getColor(R.styleable.FastColorTheme_colorFastNomal,0);
        ColorStateList colorStateList = DrawableUtil.createTabBarColorStateList(_defaultColor,_selectColor);
        Drawable _drawable = mListview.getSelector();
        Drawable _tintDrawable =  DrawableUtil.tintDrawable(_drawable,colorStateList);
        mListview.setSelector(_tintDrawable);
        //----
        ta.recycle();

        //=====================================================================
//        loadContacts();
//        if(mContactAdapter==null){
//            mContactAdapter = new ContactAdapter(getActivity(),mContacts);
//            mListview.setAdapter(mContactAdapter);
//        }else{
//            mContactAdapter.notifyDataSetChanged();
//        }
//        mListview.setOnItemClickListener(this);
//        if(LibChat.chatClient!=null){
//            LibChat.chatClient.addDataChageListener(this);
//        }
        mListview.setAdapter(new SimpleAdapter(getActivity(), getData(""),
                android.R.layout.simple_list_item_1, new String[] { "title" },
                new int[] { android.R.id.text1 }));
        mListview.setOnItemClickListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void loadContacts(){
        mContacts.clear();
        if(contactManager!=null){
            List<FContact> _copy = contactManager.getContacts();
            if(_copy!=null){
                mContacts.addAll(_copy);
            }
            return ;
        }
        List<FContact> data = new ArrayList<FContact>();
        for(int i=0;i<100;i++) {
            FContact _ct = new FContact();
            _ct.setChatId(getFtName()+(i+1));
            data.add(_ct);
        }
        mContacts.clear();
        mContacts.addAll(mContacts);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//        final FContact _select = mContacts.get(position);
//        ChatActivity.runIntentChat(getActivity(),_select.getChatId(),_select.getChatId());
        Map<String, Object> map = (Map<String, Object>)adapterView.getItemAtPosition(position);
        Intent intent = (Intent) map.get("intent");
        startActivity(intent);
    }

    //
    protected List<Map<String, Object>> getData(String prefix) {
        List<Map<String, Object>> myData = new ArrayList<Map<String, Object>>();

        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory("com.darryring.fast.FASTLITE_SAMPLE_CODE");

        PackageManager pm = getActivity().getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

        if (null == list)
            return myData;

        String[] prefixPath;
        String prefixWithSlash = prefix;

        if (prefix.equals("")) {
            prefixPath = null;
        } else {
            prefixPath = prefix.split("/");
            prefixWithSlash = prefix + "/";
        }

        int len = list.size();

        Map<String, Boolean> entries = new HashMap<String, Boolean>();

        for (int i = 0; i < len; i++) {
            ResolveInfo info = list.get(i);
            CharSequence labelSeq = info.loadLabel(pm);
            String label = labelSeq != null
                    ? labelSeq.toString()
                    : info.activityInfo.name;

            if (prefixWithSlash.length() == 0 || label.startsWith(prefixWithSlash)) {

                String[] labelPath = label.split("/");

                String nextLabel = info.activityInfo.name;

                if ((prefixPath != null ? prefixPath.length : 0) == labelPath.length - 1) {
                    addItem(myData, nextLabel, activityIntent(
                            info.activityInfo.applicationInfo.packageName,
                            info.activityInfo.name));
                } else {
                    if (entries.get(nextLabel) == null) {
                        addItem(myData, nextLabel, browseIntent(prefix.equals("") ? nextLabel : prefix + "/" + nextLabel));
                        entries.put(nextLabel, true);
                    }
                }
            }
        }

        Collections.sort(myData, sDisplayNameComparator);

        return myData;
    }

    private final static Comparator<Map<String, Object>> sDisplayNameComparator =
            new Comparator<Map<String, Object>>() {
                private final Collator collator = Collator.getInstance();

                public int compare(Map<String, Object> map1, Map<String, Object> map2) {
                    return collator.compare(map1.get("title"), map2.get("title"));
                }
            };

    protected Intent activityIntent(String pkg, String componentName) {
        Intent result = new Intent();
        result.setClassName(pkg, componentName);
        return result;
    }

    protected Intent browseIntent(String path) {
        Intent result = new Intent();
        result.setClass(getActivity(), HomeActivity.class);
        result.putExtra("com.example.android.apis.Path", path);
        return result;
    }

    protected void addItem(List<Map<String, Object>> data, String name, Intent intent) {
        Map<String, Object> temp = new HashMap<String, Object>();
        temp.put("title", name);
        temp.put("intent", intent);
        data.add(temp);
    }
}
